package com.truckdispatching.http.base;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import android.app.Application;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

public class HttpManager {

	private static HttpManager instance;

	private ConnectivityManager mConnectivityManager;

	private final int POOL_SIZE = 2;	// 普通的协议线程数
	// 下载线程池
	private ThreadPoolExecutor mHttpTaskThreadPool = null;

	private HttpManager() {
		mHttpTaskThreadPool = new ThreadPoolExecutor(POOL_SIZE, POOL_SIZE, 0L, TimeUnit.MILLISECONDS,
			new LinkedBlockingQueue<Runnable>(), new ThreadPoolExecutor.DiscardOldestPolicy());
	}

	public static HttpManager getInstance() {
		if (instance == null) {
			instance = new HttpManager();
		}
		return instance;
	}

	public void initWithApplication(Application app) {
		mConnectivityManager = (ConnectivityManager) app.getSystemService(Context.CONNECTIVITY_SERVICE);
	}

	public NetworkInfo getNetworkInfo() {
		if (mConnectivityManager != null) {
			return mConnectivityManager.getActiveNetworkInfo();
		} else {
			return null;
		}
	}

	public void sendHttpTask(HttpTask task) {
		mHttpTaskThreadPool.execute(task);
	}

	public void destory() {
		if (mHttpTaskThreadPool != null) {
			mHttpTaskThreadPool.shutdown();
			mHttpTaskThreadPool = null;
		}
	}
}
